<template>
  <div class="purchase-order-management">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">采购订单管理</h1>
      <el-button type="primary" @click="handleAdd" :icon="Plus">
        新建订单
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-card class="mb-6">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="订单编号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" clearable style="width: 200px">
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="草稿" value="draft" />
            <el-option label="待审批" value="pending" />
            <el-option label="已审批" value="approved" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card>
      <el-table :data="orderList" v-loading="loading" stripe>
        <el-table-column prop="orderNo" label="订单编号" width="150" />
        <el-table-column prop="supplierName" label="供应商" min-width="150" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            <span class="text-red-600 font-semibold">¥{{ row.totalAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="执行进度" width="120">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :stroke-width="8" />
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="expectedDate" label="期望交货日期" width="120" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)" :icon="View">
              查看
            </el-button>
            <el-button 
              v-if="row.status === 'draft'"
              type="warning" 
              size="small" 
              @click="handleEdit(row)" 
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'draft'"
              type="success" 
              size="small" 
              @click="handleSubmitApproval(row)" 
              :icon="Check"
            >
              提交审批
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              size="small" 
              @click="handleApprove(row)" 
              :icon="Check"
            >
              审批
            </el-button>
            <el-button 
              v-if="['draft', 'pending'].includes(row.status)"
              type="danger" 
              size="small" 
              @click="handleCancel(row)" 
              :icon="Close"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑订单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1200px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="order-form"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
                <el-option
                  v-for="supplier in supplierOptions"
                  :key="supplier.id"
                  :label="supplier.name"
                  :value="supplier.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="期望交货日期" prop="expectedDate">
              <el-date-picker
                v-model="form.expectedDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        
        <!-- 订单明细 -->
        <div class="order-details">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">订单明细</h3>
            <el-button type="primary" size="small" @click="handleAddItem" :icon="Plus">
              添加商品
            </el-button>
          </div>
          <el-table :data="form.items" border>
            <el-table-column prop="productCode" label="商品编码" width="120" />
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="specification" label="规格" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="{ row, $index }">
                <el-input-number
                  v-model="row.quantity"
                  :min="1"
                  :precision="2"
                  @change="calculateItemAmount($index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="{ row, $index }">
                <el-input-number
                  v-model="row.unitPrice"
                  :min="0"
                  :precision="2"
                  @change="calculateItemAmount($index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{ row }">
                <span class="text-red-600 font-semibold">¥{{ row.amount.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button type="danger" size="small" @click="handleRemoveItem($index)" :icon="Delete">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="total-amount mt-4 text-right">
            <span class="text-lg font-bold">订单总金额: </span>
            <span class="text-xl text-red-600 font-bold">¥{{ totalAmount.toLocaleString() }}</span>
          </div>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="1000px"
    >
      <div v-if="currentOrder">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentOrder.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusLabel(currentOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="text-red-600 font-semibold">¥{{ currentOrder.totalAmount.toLocaleString() }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{ currentOrder.createUser }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="期望交货日期">{{ currentOrder.expectedDate }}</el-descriptions-item>
          <el-descriptions-item label="执行进度">
            <el-progress :percentage="currentOrder.progress" :stroke-width="8" />
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="3">{{ currentOrder.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 审批流程 -->
        <div class="mt-6">
          <h3 class="text-lg font-semibold mb-4">审批流程</h3>
          <el-steps :active="getApprovalStep(currentOrder.status)" finish-status="success">
            <el-step title="创建订单" description="订单创建完成" />
            <el-step title="提交审批" description="等待审批" />
            <el-step title="审批通过" description="订单审批通过" />
            <el-step title="执行订单" description="订单执行中" />
            <el-step title="订单完成" description="订单执行完成" />
          </el-steps>
        </div>

        <!-- 订单明细 -->
        <div class="mt-6">
          <h3 class="text-lg font-semibold mb-4">订单明细</h3>
          <el-table :data="currentOrder.items" border>
            <el-table-column prop="productCode" label="商品编码" width="120" />
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="specification" label="规格" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="{ row }">
                ¥{{ row.unitPrice.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{ row }">
                <span class="text-red-600 font-semibold">¥{{ row.amount.toLocaleString() }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 商品选择对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      title="选择商品"
      width="800px"
    >
      <el-table :data="productOptions" @row-click="handleSelectProduct">
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="specification" label="规格" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="price" label="参考价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price.toLocaleString() }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  View,
  Check,
  Close
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const productDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const currentOrder = ref(null)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  supplierId: '',
  status: '',
  dateRange: []
})

// 订单表单
const form = reactive({
  id: null,
  orderNo: '',
  supplierId: '',
  expectedDate: '',
  remark: '',
  items: []
})

// 表单验证规则
const rules = {
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  expectedDate: [
    { required: true, message: '请选择期望交货日期', trigger: 'change' }
  ]
}

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 订单列表
const orderList = ref([])

// 供应商选项
const supplierOptions = ref([
  { id: 1, name: '北京科技有限公司' },
  { id: 2, name: '上海制造集团' },
  { id: 3, name: '广州贸易公司' }
])

// 商品选项
const productOptions = ref([
  { code: 'P001', name: '笔记本电脑', specification: '15寸', unit: '台', price: 5000 },
  { code: 'P002', name: '办公桌', specification: '1.2m', unit: '张', price: 800 },
  { code: 'P003', name: '打印机', specification: 'A4', unit: '台', price: 1200 },
  { code: 'P004', name: '办公椅', specification: '人体工学', unit: '把', price: 600 }
])

// 计算订单总金额
const totalAmount = computed(() => {
  return form.items.reduce((total, item) => total + (item.amount || 0), 0)
})

// 获取状态类型
const getStatusType = (status: string) => {
  const types = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    executing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labels = {
    draft: '草稿',
    pending: '待审批',
    approved: '已审批',
    executing: '执行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return labels[status] || '未知'
}

// 获取审批步骤
const getApprovalStep = (status: string) => {
  const steps = {
    draft: 0,
    pending: 1,
    approved: 2,
    executing: 3,
    completed: 4,
    cancelled: 1
  }
  return steps[status] || 0
}

// 生成订单编号
const generateOrderNo = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `PO${year}${month}${day}${random}`
}

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const mockData = [
      {
        id: 1,
        orderNo: 'PO202401150001',
        supplierId: 1,
        supplierName: '北京科技有限公司',
        totalAmount: 15000,
        status: 'approved',
        progress: 60,
        createUser: '张三',
        createTime: '2024-01-15 10:30:00',
        expectedDate: '2024-01-25',
        remark: '紧急采购',
        items: [
          {
            productCode: 'P001',
            productName: '笔记本电脑',
            specification: '15寸',
            unit: '台',
            quantity: 3,
            unitPrice: 5000,
            amount: 15000
          }
        ]
      },
      {
        id: 2,
        orderNo: 'PO202401200002',
        supplierId: 2,
        supplierName: '上海制造集团',
        totalAmount: 8000,
        status: 'pending',
        progress: 0,
        createUser: '李四',
        createTime: '2024-01-20 14:20:00',
        expectedDate: '2024-02-01',
        remark: '',
        items: [
          {
            productCode: 'P002',
            productName: '办公桌',
            specification: '1.2m',
            unit: '张',
            quantity: 10,
            unitPrice: 800,
            amount: 8000
          }
        ]
      },
      {
        id: 3,
        orderNo: 'PO202402010003',
        supplierId: 3,
        supplierName: '广州贸易公司',
        totalAmount: 1800,
        status: 'completed',
        progress: 100,
        createUser: '王五',
        createTime: '2024-02-01 09:15:00',
        expectedDate: '2024-02-10',
        remark: '质量要求高',
        items: [
          {
            productCode: 'P003',
            productName: '打印机',
            specification: 'A4',
            unit: '台',
            quantity: 1,
            unitPrice: 1200,
            amount: 1200
          },
          {
            productCode: 'P004',
            productName: '办公椅',
            specification: '人体工学',
            unit: '把',
            quantity: 1,
            unitPrice: 600,
            amount: 600
          }
        ]
      }
    ]
    
    orderList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getOrderList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    supplierId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 新增订单
const handleAdd = () => {
  dialogTitle.value = '新建采购订单'
  Object.assign(form, {
    id: null,
    orderNo: generateOrderNo(),
    supplierId: '',
    expectedDate: '',
    remark: '',
    items: []
  })
  dialogVisible.value = true
}

// 编辑订单
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑采购订单'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 查看订单详情
const handleView = (row: any) => {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 提交审批
const handleSubmitApproval = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要提交订单 "${row.orderNo}" 审批吗？`,
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('提交审批成功')
    getOrderList()
  } catch (error) {
    // 用户取消
  }
}

// 审批订单
const handleApprove = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要审批通过订单 "${row.orderNo}" 吗？`,
      '确认审批',
      {
        confirmButtonText: '通过',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('审批通过')
    getOrderList()
  } catch (error) {
    // 用户取消
  }
}

// 取消订单
const handleCancel = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 "${row.orderNo}" 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('订单已取消')
    getOrderList()
  } catch (error) {
    // 用户取消
  }
}

// 添加商品
const handleAddItem = () => {
  productDialogVisible.value = true
}

// 选择商品
const handleSelectProduct = (product: any) => {
  const existingItem = form.items.find(item => item.productCode === product.code)
  if (existingItem) {
    ElMessage.warning('该商品已存在')
    return
  }
  
  form.items.push({
    productCode: product.code,
    productName: product.name,
    specification: product.specification,
    unit: product.unit,
    quantity: 1,
    unitPrice: product.price,
    amount: product.price
  })
  
  productDialogVisible.value = false
}

// 移除商品
const handleRemoveItem = (index: number) => {
  form.items.splice(index, 1)
}

// 计算商品金额
const calculateItemAmount = (index: number) => {
  const item = form.items[index]
  item.amount = item.quantity * item.unitPrice
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (form.items.length === 0) {
      ElMessage.warning('请添加订单明细')
      return
    }
    
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(form.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    getOrderList()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  form.items = []
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getOrderList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  getOrderList()
}

// 组件挂载时获取数据
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.purchase-order-management {
  padding: 20px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.order-form .el-select {
  width: 100%;
}

.order-details {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.total-amount {
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.text-red-600 {
  color: #dc2626;
}

.font-semibold {
  font-weight: 600;
}

.font-bold {
  font-weight: 700;
}
</style>